//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { useSeaOtterStores } from "./store";
import { get_session } from "@/api/user";
import { request } from "@/utils/request";
import { gen_access_token } from "@/api/project_server";
import type { AuthSecretInfo } from "@/api/dragonfly/config";
import { list as list_auth_secret, remove as remove_auth_secret } from "@/api/seaotter/auth_secret";
import { Button, Card, List, message, Modal, Popover, Space } from "antd";
import EditSecretModal from "./components/EditSecretModal";
import { CopyOutlined, MoreOutlined } from "@ant-design/icons";
import { writeText } from "@tauri-apps/api/clipboard";

const AuthSecretPanel = () => {
    const appStore = useSeaOtterStores();

    const [secretList, setSecretList] = useState<AuthSecretInfo[]>([]);
    const [showAddModal, setShowAddModal] = useState(false);
    const [updateSecretInfo, setUpdateSecretInfo] = useState<AuthSecretInfo | null>(null);
    const [removeSecretInfo, setRemoveSecretInfo] = useState<AuthSecretInfo | null>(null);


    const loadSecretList = async () => {
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));
        const res = await request(list_auth_secret(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
        }));
        setSecretList(res.auth_secret_list);
    };

    const removeSecret = async () => {
        if (removeSecretInfo == null) {
            return;
        }
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));
        await request(remove_auth_secret(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            username: removeSecretInfo.username,
        }));
        message.info("删除成功");
        await loadSecretList();
        setRemoveSecretInfo(null);
    };


    useEffect(() => {
        if (appStore.myPerm != null && appStore.myPerm.manage_auth_secret) {
            loadSecretList();
        } else {
            setSecretList([]);
        }
    }, [appStore.myPerm]);
    return (
        <>
            <Card title={<span style={{ fontSize: "16px", fontWeight: 600 }}>验证密钥列表</span>} bordered={false}
                bodyStyle={{ padding: "10px 20px" }}
                extra={
                    <Button type="primary" onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowAddModal(true);
                    }}>增加验证密钥</Button>
                }>
                <List rowKey="username" dataSource={secretList} grid={{ gutter: 16 }}
                    pagination={false} renderItem={item => (
                        <Space style={{ backgroundColor: "#eee", marginRight: "10px", padding: "10px 10px", borderRadius: "6px" }}>
                            <div style={{ width: "200px" }}>
                                用户名&nbsp;{item.username}
                            </div>
                            <Space>
                                <Button type="link" icon={<CopyOutlined />} title="复制密钥" onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    writeText(item.password);
                                    message.info("已复制密钥");
                                }} />
                                <Popover placement="bottom" trigger="click" content={
                                    <Space direction="vertical">
                                        <Button type="link" disabled={!(appStore.myPerm?.manage_auth_secret)}
                                            onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                setUpdateSecretInfo(item);
                                            }}>修改</Button>
                                        <Button type="link" danger disabled={!(appStore.myPerm?.manage_auth_secret)}
                                            onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                setRemoveSecretInfo(item);
                                            }}>删除</Button>
                                    </Space>
                                }>
                                    <MoreOutlined />
                                </Popover>
                            </Space>
                        </Space>
                    )} />
            </Card >

            {showAddModal == true && (
                <EditSecretModal onCancel={() => setShowAddModal(false)} onOk={() => {
                    setShowAddModal(false);
                    loadSecretList();
                }} />
            )}
            {updateSecretInfo != null && (
                <EditSecretModal secret={updateSecretInfo} onCancel={() => setUpdateSecretInfo(null)} onOk={() => {
                    setUpdateSecretInfo(null);
                    loadSecretList();
                }} />
            )}
            {removeSecretInfo != null && (
                <Modal open title="删除验证密钥" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveSecretInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeSecret();
                    }}>
                    使用删除验证密钥&nbsp;{removeSecretInfo.username}&nbsp;?
                </Modal>
            )}
        </>
    );
};

export default observer(AuthSecretPanel);